/*
 * File:   newmainp33.c
 * Author: ruben
 *
 * Created on 10. März 2011, 07:33
 */

#include <p33Fxxxx.h>
#include <uart.h>

#define FCY 37000000
#define IDLE_LINE_TIMEOUT 11200
#define BAUDRATE 38400
#define BRGVAL ((FCY/BAUDRATE)/16)-1

void initClock(void);
void initUart(void);

_FOSCSEL(FNOSC_FRC);
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF & POSCMD_NONE);
// Clock Switching is enabled and Fail Safe Clock Monitor is disabled
// OSC2 Pin Function: OSC2 is Clock Output
// Primary Oscillator Mode: XT Crystanl

_FWDT(FWDTEN_OFF); // Watchdog Timer Enabled/disabled by user software

void __attribute__((__interrupt__, auto_psv)) _T2Interrupt(void)
{
    PORTAbits.RA0 ^= 1;
    
    IFS0bits.T2IF = 0;
}

int main(void) {
    
    TRISAbits.TRISA0 = 0;
    PORTAbits.RA0 = 0;

    initClock();
    initUart();

     /*
     * Konfiguriere Timer 2
     * bewirkt Idle-Line-Timeout (280us)
     */
    T2CON = 0;
    PR2 = IDLE_LINE_TIMEOUT;
    IFS0bits.T2IF = 0;
    IEC0bits.T2IE = 1;
    IPC1bits.T2IP = 1;
    TMR2 = 0;
    T2CONbits.TON = 1;

    int i;
    while(1){
        for(i=0; i<10000;i++);
        T2CONbits.TON ^= 1;
    }
    return 0;
}



void initClock(void) {
    //Konfiguriere Clock für 37Mhz

    PLLFBD = 38; // M = 40
    CLKDIVbits.PLLPOST = 0; // N1 = 2
    CLKDIVbits.PLLPRE = 0; // N2 = 2
    OSCTUN = 0;
    RCONbits.SWDTEN = 0;

    // Clock switch to incorporate PLL
    __builtin_write_OSCCONH(0x01); // Initiate Clock Switch to
    // FRC with PLL (NOSC=0b001)
    __builtin_write_OSCCONL(0x01); // Start clock switching
    while (OSCCONbits.COSC != 0b001); // Wait for Clock switch to occur

    while (OSCCONbits.LOCK != 1) {};
}

void initUart(void) {
    /*
     * Konfiguriere UART2 DEBUG
     */

    U2MODE = 0;
    U2STA = 0;
    U2BRG = BRGVAL;
    U2MODEbits.UARTEN = 1;
    U2STAbits.UTXEN = 1;

    /*
     * Konfiguriere UART1
     * Kommunikation mit Sensor-Master
     */
    U1MODE = 0;
    U1STA = 0;
    U1BRG = BRGVAL;
    U1MODEbits.UARTEN = 1;
    U1STAbits.UTXEN = 1;
}
